package com.xeecos
{
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;

	public class Uploader extends EventDispatcher
	{
		private var _file:File = new File();
		private var _result:String="";
		private var _progress:Number=0;
		public function Uploader()
		{
			_file.addEventListener(Event.SELECT,onSelected);
			_file.addEventListener(ProgressEvent.PROGRESS,onProgress);
			_file.addEventListener(IOErrorEvent.IO_ERROR,onIOError);
			_file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA,onUploadComplete);
		}
		public function openFile():void{
			_file.browse();
		}
		public function get nativePath():String{
			return _file.nativePath;
		}
		public function get result():String{
			return _result;
		}
		public function get progress():Number{
			return _progress;
		}
		private function onSelected(evt:Event):void{
			this.dispatchEvent(new Event(Event.SELECT));
			_file.addEventListener(Event.COMPLETE,onComplete);
			_file.load();
		}
		private function onProgress(evt:ProgressEvent):void{
			_progress = evt.bytesLoaded/evt.bytesTotal*100;
			this.dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS));
		}
		private function onIOError(evt:IOErrorEvent):void{
			_result = "error";
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		private function onComplete(evt:Event):void{
			_file.removeEventListener(Event.COMPLETE,onComplete);
			var req:URLRequest = new URLRequest();
			req.url = "http://1.starrynightwalk.sinaapp.com/mobile/ios/app_upload.php";
			_file.upload(req,"uploadedfile",false);
		}
		private function onUploadComplete(evt:DataEvent):void{
			_result = evt.data;
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}